/**
 * ReadClassFromFile.java 2008-05-16
 *        
 * Linker is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package linker.plugin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Read a class from a file and return the intense of it.
 * 
 * @version 2008-05-27
 * @author Jianfeng tujf.cn@gmail.com
 * 
 */

public class PluginClassLoader extends ClassLoader {

	/**
	 * The singeton classLoader.
	 */
	private static PluginClassLoader classLoader;

	/**
	 * 
	 * @return The single classLoader.
	 */
	public static final PluginClassLoader getClassLoader() {
		if (classLoader == null) {
			classLoader = new PluginClassLoader();
		}

		return classLoader;
	}

	/**
	 * Find class by the given file.
	 * 
	 * @param file
	 *            The given file
	 * @return The found class.
	 */
	public final Class< ? > findClass(final File file) {
		byte[] b = loadClassData(file);

		String name = file.getName();
		name = name.substring(0, name.indexOf("."));
		name = "linker.plugin." + name;

		return defineClass(name, b, 0, b.length);
	}

	/**
	 * Get the class file by the Given name.
	 * 
	 * @param file
	 *            The given file.
	 * @return The class file.
	 */
	private byte[] loadClassData(final File file) {
		java.io.FileInputStream in;
		byte[] bytes = null;

		try {
			in = new java.io.FileInputStream(file);

			bytes = new byte[in.available()];
			in.read(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return bytes;
	}

}
